package dahlpay

import (
    "fmt"
	"time"
	"errors"
	"strconv"
	"thirdpaysdk/core"
	"crypto/md5"
)

//小程序统一下单
type UnifieldReq struct { 
	Chid    string   `json:"chid"`    //渠道编码      
	Ext     string   `json:"ext"`     //渠道订单号
	Fee     string   `json:"fee"`     //支付金额
	Timeamp string   `json:"timeamp"` //时间戳(年年年年月月日日时时分分秒秒)
	Sign    string   `json:"sign"`    //数字签名
	OpenId  string   `json:"openid"`  //微信小程序返回的openId
	Ali     string   `json:"ali,omitempty"`     //
}

type WXMicroPay struct { 
	TimeStamp string `json:"timeStamp"`
	Package   string `json:"package"`
	PaySign   string `json:"paySign"`
	AppId     string `json:"appId"`
	SignType  string `json:"signType"`
	NonceStr  string `json:"nonceStr"`
}

type UnifiedRsp struct {
	ErrCode    string      `json:"errcode"`
	ErrMsg     string      `json:"errmsg"`
	WXMicroPay *WXMicroPay `json:"WXMicroPay,omitempty"`
}

/*
{"errcode":"1000","errmsg":"SUCCESS", "WXMicroPay":{"timeStamp":"1538198248","package":"prepay_id=wx291317287835000fdaea0f891979481549","paySign":"B2A3234340F9FCB1C96D576379022E8E","appId":"wxf57e9bafff563411","signType":"MD5","nonceStr":"kKgoCKxhmNkTb7dLKPxVAekcxLArQd"}}
*/

func makeReqMd5Sign(chid,ext,fee,timeamp,appSecret string) string {
	str := fmt.Sprintf("chid=%s&ext=%s&fee=%s&timeamp=%s%s",chid,ext,fee,timeamp,appSecret)
	return fmt.Sprintf("%X", md5.Sum([]byte(str)))
}

func  Unifield(mchId,appSecret string,fee float32,orderId, openId, ali string) (UnifiedRsp, error){
	incompleteURL := "http://alid.dahl.ltd/paycenter/req?chid=%s&fee=%s&ext=%s&timeamp=%s&sign=%s&openid=%s"
	curTime := time.Now().Format("20060102150405")
	feeStr :=  strconv.FormatFloat(float64(fee), 'f', -1, 32)
	sign := makeReqMd5Sign(mchId,orderId,feeStr,curTime,appSecret)
	serverUrl := fmt.Sprintf(incompleteURL, mchId, feeStr, orderId, curTime, sign, openId)
	var rsp UnifiedRsp
	client := core.GetPayJSONClient("GET", serverUrl)
	_, err := client.PayJsonExcute(nil, &rsp)
    if err != nil {
		return rsp, err
	}
	if rsp.ErrCode != "1000" {
	    message := rsp.ErrCode + ":" + rsp.ErrMsg
	    return rsp, errors.New(message)
	}
	return rsp, nil
}
